/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
export var reorderList = function (head) {
  if (!head || !head.next) return head
  let middle = middleNode(head)
  let right = middle.next
  middle.next = null
  right = reverseList(right)
  let left = head
  while (left && right) {
    let leftNext = left.next
    let rightNext = right.next
    left.next = right
    right.next = leftNext
    left = leftNext
    right = rightNext
  }
}

var middleNode = head => {
  let slow = head
  let fast = head
  while (fast.next && fast.next.next) {
    slow = slow.next
    fast = fast.next.next
  }
  return slow
}

var reverseList = head => {
  let prev = null
  let curr = head
  while (curr) {
    let next = curr.next
    curr.next = prev
    prev = curr
    curr = next
  }
  return prev
}
